package zencstudio.sgrealtor.view.phone;

import java.util.List;

import zencstudio.sgrealtor.R;
import zencstudio.sgrealtor.adapter.PropertyGirdViewAdapter;
import zencstudio.sgrealtor.model.Property;
import zencstudio.sgrealtor.service.IWireFrameService;
import zencstudio.sgrealtor.service.WireFrameServiceFactory;
import zencstudio.sgrealtor.utils.Const;
import zencstudio.sgrealtor.utils.WFErrorCode;
import zencstudio.sgrealtor.utils.WFUtils;
import zencstudio.sgrealtor.view.common.BaseActivity;
import zencstudio.sgrealtor.view.common.CloseConfirmDlg;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

public class MainActivity extends BaseActivity {
	private GridView gridView;
	//private StaggeredGridView gridView;
	private PropertyGirdViewAdapter adapter;
	private boolean loadingMore = true;
	private int page = 1;
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		if(!WFUtils.checkInternetConnection(this)){
			showNetworkErrorDlg();
			return;
		}
		TextView title = (TextView) findViewById(R.id.txtTitle);
		title.setText(getString(R.string.home));
		gridView = (GridView) findViewById(R.id.gridPropety);
		//gridView = (GridView) findViewById(R.id.gridPropety);
		adapter = new PropertyGirdViewAdapter(this);
		gridView.setAdapter(adapter);
		initControls();
		loadData();
	}
	@Override
	protected void initUI() {
		setContentView(R.layout.activity_main);
		
	}	
	private void initControls(){
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Property p = (Property) adapter.getItem(arg2);
				Intent intent = new Intent(MainActivity.this,PropertyDetailActivity.class);
				intent.putExtra(Const.PROPERTYID, p.getId());
				startActivity(intent);
			}
		});
		gridView.setOnScrollListener(new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int lastInScreen = firstVisibleItem + visibleItemCount;
				//Log.d("lastInScreen", lastInScreen+"");
				//Log.d("totalItemCount",totalItemCount+"");
				//Log.d("loadingMore",loadingMore+"");
				if((lastInScreen == totalItemCount) && !(loadingMore)){
					Thread thread =  new Thread(null, loadMoreProperty);
					thread.start();
				}
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		super.onKeyDown(keyCode, event);
	    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	    	CloseConfirmDlg frm = new CloseConfirmDlg(this);
	    	frm.show();
	    	return true;
	    }
		return super.onKeyDown(keyCode, event);
	}
	private void loadData(){
		showProgressDlg();
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				IWireFrameService service = WireFrameServiceFactory.getInstance().getService();
				List<Property> properties = null;
				Message msg = handler.obtainMessage();
				try {
					properties = service.getProperties(page, 10);
				} catch (Exception e) {
					e.printStackTrace();
					msg.arg1 = WFErrorCode.NETWORK_ERROR.getValue();
				}
				msg.obj = properties;
				handler.sendMessage(msg);
			}
		});
		thread.start();
	}
	private Handler handler = new Handler(){
		public void handleMessage (Message msg){
			dismissProgressDlg();
			if(msg.arg1==WFErrorCode.NETWORK_ERROR.getValue()){
				showNetworkErrorDlg();
				return;
			}
			if(msg.obj!=null){
				adapter.addProperties((List<Property>) msg.obj);
				adapter.notifyDataSetChanged();
				page++;
				loadingMore = false;
				
			}
		}
	};

	private Runnable loadMoreProperty = new Runnable() {
		
		@Override
		public void run() {
			Log.d("loadMoreProperty", "load more page="+page);
			loadingMore = true;
			IWireFrameService service = WireFrameServiceFactory.getInstance().getService();
			List<Property> properties = null;
			try {
				properties = service.getProperties(page, 10);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Message msg = handler.obtainMessage();
			msg.obj = properties;
			handler.sendMessage(msg);
		}
	};
}
